<?php
session_start(); 

	function sanitize($data)
	{
		$data=trim($data);
		$data=htmlspecialchars($data);
		$data=pg_escape_string($data);
		return $data;
	}

require('parametros/bd.php');
if (($_SESSION['logged_in'])==TRUE) 
{
	$iprecreate= $_SERVER['REMOTE_ADDR'];
	$useragentrecreate=$_SERVER["HTTP_USER_AGENT"];
	$signaturerecreate=$_SESSION['signature'];
	$saltrecreate = substr($signaturerecreate, 0, $length_salt);
	$originalhash = substr($signaturerecreate, $length_salt, 40);
	$hashrecreate= sha1($saltrecreate.$iprecreate.$useragentrecreate);
	if (!($hashrecreate==$originalhash)) 
	{
		header(sprintf("Location: %s", $forbidden_url));	
		exit; 
	}
	if ((isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $sessiontimeout)))  
	{
		session_destroy();   
		session_unset();
		$redirectback=$domain.'index.php';
		header(sprintf("Location: %s", $redirectback));
	}  
	$_SESSION['LAST_ACTIVITY'] = time(); 
}
$validationresults=TRUE;
$registered=TRUE;
$recaptchavalidation=TRUE;
$iptocheck= $_SERVER['REMOTE_ADDR'];
$iptocheck= pg_escape_string($iptocheck);
if ($fetch = pg_fetch_array( pg_query("SELECT loggedip FROM ipcheck WHERE loggedip='$iptocheck'"))) 
{
	$resultx = pg_query("SELECT failedattempts FROM ipcheck WHERE loggedip='$iptocheck'");
	$rowx = pg_fetch_array($resultx);
	$loginattempts_total = $rowx['failedattempts'];
	If ($loginattempts_total>$maxfailedattempt) 
	{
		header(sprintf("Location: %s", $forbidden_url));	
		exit;
	}
}

if (!isset($_SESSION['logged_in']))
{
    $_SESSION['logged_in'] = FALSE;
}

if ((isset($_POST["pass"])) && (isset($_POST["user"])) && ($_SESSION['LAST_ACTIVITY']==FALSE)) 
{
/*	function sanitize($data)
	{
		$data=trim($data);
		$data=htmlspecialchars($data);
		$data=pg_escape_string($data);
		return $data;
	} */
}

$user= sanitize($_POST["user"]);
$pass= sanitize($_POST["pass"]);
$pass = md5($pass);
//modifiq
$_SESSION['user'] =$user;

if (!($fetch = pg_fetch_array( pg_query("SELECT username FROM authentication WHERE username='$user'"))))
{
	$registered=FALSE;
	
}

if ($registered==TRUE) 
{
	$result1 = pg_query("SELECT loginattempt FROM authentication WHERE username='$user'");
	$row = pg_fetch_array($result1);
	$loginattempts_username = $row['loginattempt'];
}

//aqui si no funciona preguntar por password == base de datos

if ($registered==TRUE)
{
		$resultado = pg_query("SELECT admin FROM authentication WHERE username='$user'");
		$fila = pg_fetch_array ($resultado);
		$_SESSION['admin'] = $fila['admin'];
		
		$result = pg_query("SELECT password FROM authentication WHERE username='$user'");
		$row = pg_fetch_array($result);
		$correctpassword = $row['password'];
		if ($row['password'] == $pass)
		{
			$userhash = 1;
			$correcthash = 1;
		}
		/*
		$salt = substr($correctpassword, 0, 64);
		$correcthash = substr($correctpassword, 64, 64);
		$userhash = hash("sha256", $salt . $pass); */
}



if ((!($userhash == $correcthash)) || ($registered==FALSE) || ($recaptchavalidation==FALSE)) 
{
	$validationresults=FALSE;

	if ($registered==TRUE) 
	{
		$loginattempts_username= $loginattempts_username + 1;
		$loginattempts_username=intval($loginattempts_username);
		pg_query("UPDATE authentication SET loginattempt = '$loginattempts_username' 
		WHERE username = '$user'");

		if (!($fetch = pg_fetch_array( pg_query("SELECT loggedip FROM ipcheck WHERE loggedip='$iptocheck'")))) 
		{
			$loginattempts_total=1;
			$loginattempts_total=intval($loginattempts_total);
			pg_query("INSERT INTO ipcheck (loggedip, failedattempts) VALUES ('$iptocheck', '$loginattempts_total')");	
		} 
		else
		{
			$loginattempts_total= $loginattempts_total + 1;
			pg_query("UPDATE ipcheck SET failedattempts = '$loginattempts_total' 
			WHERE loggedip = '$iptocheck'");
		}
	}

	if ($registered==FALSE) 
	{
		if (!($fetch = pg_fetch_array( pg_query("SELECT loggedip FROM ipcheck WHERE loggedip='$iptocheck'")))) 
		{
			$loginattempts_total=1;
			$loginattempts_total=intval($loginattempts_total);
			pg_query("INSERT INTO ipcheck (loggedip, failedattempts) 
			VALUES ('$iptocheck', '$loginattempts_total')");	
		}
		else 
		{
			$loginattempts_total= $loginattempts_total + 1;
			pg_query("UPDATE ipcheck SET failedattempts = '$loginattempts_total' 
			WHERE loggedip = '$iptocheck'");
		}
	}
} 
else 
{
	//el usuario inicio sesion
	//reseteamos algun intento fallido que tenga 
	
	$loginattempts_username=0;
	$loginattempts_total=0;
	$loginattempts_username=intval($loginattempts_username);
	$loginattempts_total=intval($loginattempts_total);
	pg_query("UPDATE authentication SET loginattempt = '$loginattempts_username' 
	WHERE username = '$user'");
	pg_query("UPDATE ipcheck SET failedattempts = '$loginattempts_total' 
	WHERE loggedip = '$iptocheck'");
	
	function genRandomString() {
	//credits: http://bit.ly/a9rDYd
	    $length = 50;
	    $characters = "0123456789abcdef";      
	    for ($p = 0; $p < $length ; $p++) {
	        $string .= $characters[mt_rand(0, strlen($characters))];
	    }
	    
	    return $string;
	}
	
	$random=genRandomString();
	$salt_ip= substr($random, 0, $length_salt);
	$useragent=$_SERVER["HTTP_USER_AGENT"];
	$hash_user= sha1($salt_ip.$iptocheck.$useragent);
	$signature= $salt_ip.$hash_user;
	session_regenerate_id();
	$_SESSION['signature'] = $signature;
	$_SESSION['logged_in'] = TRUE;
	$_SESSION['LAST_ACTIVITY'] = time(); 
}

if (!$_SESSION['logged_in']): 

?>

<!DOCTYPE HTML>
<html>

<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/mootools.js"></script>
		<script type="text/javascript" src="js/imageMenu.js"></script>
		<script type="text/javascript" src="js/ajax.js"></script>
		<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
		<link href="css/imageMenu.css" rel="stylesheet" type="text/css" />
</head>
<body >
<?php
	include 'encabezado.php';
?>
<div id="rightBuscar">
	<form name="frmbusqueda" id="searchbox" action="" onsubmit="buscarDato(); return false">
		    <input id="search" name="dato" type="text">
		    <input id="submit" type="submit" value="Search">
	</form>
	
	<h2 id="tituloNaranjaO"> Registrarse <a href="register.php">AQUI</a></h2>
	
</div>

<div id="loginCaja">
	<div id="content">
	  <div id="innerholder">
	<h1 id="tituloNaranja">Por Favor Ingrese Su Usuario/Contrase&ntilde;a</h1>
	<br /><br />
	<!-- START OF LOGIN FORM -->
	<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
	<table>
	  <tr>
		 <td>
		 	<div id="labelLogin">Usuario:</div>
		 </td>
		  <td>
		  	<input id="search" type="text" class="<?php if ($validationresults==FALSE) echo "invalid"; ?>" id="user" name="user">
		  </td>
	  </tr>
	  <tr>
	    <td>
	    	<div id="labelLogin">Contrase&ntilde;a:</div>
	    </td>
	    <td>
	    	<input id="search" name="pass" type="password" class="<?php if ($validationresults==FALSE) echo "invalid"; ?>" id="pass" >
	    </td>
	  </tr>
	  <tr>
	    <td colspan="2">
	    <?php if (($loginattempts_username > 2) || ($registered==FALSE) || ($loginattempts_total>2)) { ?>
		<?php } ?>
		<?php if ($validationresults==FALSE) echo '<h2 id="mensajeLogin">Por favor, ingrese un usuario/contrase&ntilde;a validos (son requeridos).</h2>'; ?><br />
	     </td>
	   </tr>
	     <tr>
	    <td> </td>
	    <td><input type="submit" value="Login" id="submitLogin">   </td>
	   </tr>
	</table>
	                 
	</form>
	<!-- END OF LOGIN FORM -->
	<br />
	<br />
	</div>
	</div>
	
</div>	

		
<fieldset>
	<div id="buscar">
		<h2 id="tituloNaranja2">Libros Destacados de la Semana</h2>
			<div id="kwick">
				<ul class="kwicks">
					<li><a class="kwick opt1" href="libro.php?isbn=9788484417552"  ></a></li>
					<li><a class="kwick opt2" href="libro.php?isbn=9788426419804"  ></a></li>
					<li><a class="kwick opt3" href="libro.php?isbn=9788493801311" ></a></li>
					<li><a class="kwick opt4" href="libro.php?isbn=9788423345540"  ></a></li>
					<li><a class="kwick opt5" href="libro.php?isbn=9788401352256"  ></a></li>
					<li><a class="kwick opt6" href="libro.php?isbn=9788401352255"  ></a></li>
					<li><a class="kwick opt7" href="libro.php?isbn=9788401452255"  ></a></li>
				</ul>
			</div>
			
			<script type="text/javascript">
				var myMenu = new ImageMenu($$('#kwick .kwick'),{openWidth:200});
			</script>
	</div>
</fieldset>

<?php
include 'pie.php';
exit();
endif;
?>